package com.authorization.demo.controller;

import com.authorization.demo.entity.UserRole;
import com.authorization.demo.exception.TokenException;
import com.authorization.demo.request.FindUserRequest;
import com.authorization.demo.entity.UserTable;
import com.authorization.demo.request.LoginForm;
import com.authorization.demo.service.MenuService;
import com.authorization.demo.service.UserRoleService;
import com.authorization.demo.service.UserTableService;
import com.authorization.demo.utils.MD5Utils;
import com.authorization.demo.utils.TokenUtils;
import com.authorization.demo.vo.R;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.*;

/**
 * @Remarks:
 * @ClassName: UserTableController
 * @Author: Micora
 * @CreateTime: 2022/7/13
 */
@CrossOrigin //开放跨域访问
@RestController
@RequestMapping("/user")
@Api(tags = "用户管理")
public class UserTableController {

    @Resource
    private UserTableService userTableService;

    @Resource
    private UserRoleService userRoleService;

    @Resource
    private MenuService menuService;

    //登录
    @ApiOperation("登录")
    @PostMapping("/loginInto")
    public R loginInto(@RequestBody LoginForm loginForm) {

        UserTable userTable = userTableService.getById(loginForm.getUserName());
        if (userTable != null && userTable.getPassword().equals(loginForm.getPassword()) && userTable.getStatus()== 1) {
            List<String> userMenuList = menuService.findUsermenu(loginForm.getUserName());
            return R.ok()
                    .data("token",TokenUtils.token(loginForm.getUserName()
                                    ,loginForm.getPassword()
                                    ,userMenuList))
                    .data("username",loginForm.getUserName());
        }
        return R.ok().setCode(401).setMessage("账号或密码错误");
    }

    //查询分配的角色
    @ApiOperation("查询分配的角色")
    @PostMapping("/userRoleFind")
    public R userRoleFind(@RequestParam String userName,@RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "分配角色");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        List<String> roleNameList = new ArrayList<>();
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USER_NAME", userName);
        List<UserRole> userRoles = userRoleService.list(queryWrapper);
        Iterator<UserRole> iterator = userRoles.iterator();
        while (iterator.hasNext()) {
            UserRole userRole = iterator.next();
            roleNameList.add(userRole.getRoleName());
        }
        return R.ok().data("roleNameList", roleNameList);
    }

    //分配角色
    @ApiOperation("分配角色")
    @PostMapping("/userRole")
    public R userRole(@RequestParam String userName, @RequestParam String[] roleNames, @RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "分配角色");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        List<UserRole> userRoleList = new ArrayList<>();
        QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("USER_NAME", userName);
        userRoleService.remove(queryWrapper);
        for (String roleName : roleNames) {
            UserRole userRole = new UserRole(userName, roleName);
            userRoleList.add(userRole);
        }
        if (userRoleService.saveBatch(userRoleList)) {
            return R.ok();
        }
        return R.error().setMessage("重新分配角色出现问题");
    }

    //配合接口做的测试
    @ApiOperation("全部查询的简单测试接口")
    @GetMapping("/findAllTest")
    public R findAll(@RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "查询用户");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
//        QueryWrapper<UserTable> queryWrapper = new QueryWrapper<>();
        //queryWrapper.orderByDesc("CREATE_DATE");
//        IPage<UserTable> userPage = new Page<>(1, 20);//参数一是当前页，参数二是每页个数
//        userPage = userTableService.page(userPage, queryWrapper);
//        List<UserTable> listByPage = userPage.getRecords();
        List<UserTable> listByPage = userTableService.list();

        return R.ok().data("listByPage", listByPage);
    }

    //用户管理首页的查询
    @ApiOperation("带条件分页查询")
    @PostMapping("/findList")
    public R findList(@RequestBody FindUserRequest findRequest, @RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "查询用户");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        QueryWrapper<UserTable> queryWrapper = new QueryWrapper<>();
        if (findRequest.userName != null) {
            queryWrapper.like("USER_NAME", findRequest.userName);
        }
        if (findRequest.name != null) {
            queryWrapper.like("NAME", findRequest.name);
        }
        if (findRequest.status != 0) {
            queryWrapper.eq("STATUS", findRequest.status);
        }
        if (findRequest.createDate1 != null && findRequest.createDate2 != null) {
            queryWrapper.between("CREATE_DATE", findRequest.createDate1, findRequest.createDate2);
        }else if (findRequest.createDate1 != null){
            queryWrapper.between("CREATE_DATE", findRequest.createDate1, new Date());
        }else if (findRequest.createDate2 != null){
            queryWrapper.between("CREATE_DATE", new Date(), findRequest.createDate2);
        }

        List<UserTable> userTableList = userTableService.list(queryWrapper);

        return R.ok().data("userTableList", userTableList);

    }

    //创建用户
    @ApiOperation("创建用户")
    @PostMapping("/createUser")
    public R createUser(@RequestBody UserTable userTable,@RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "创建用户");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        if (userTableService.FindOneIsExist(userTable.getUserName())) {
            return R.ok().setCode(403).setMessage("用户已存在");
        }
//        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
//        userTable.setCreateDate(new Date());
//        userTable.setAlterDate(new Date());
//        userTable.setPassword(MD5Utils.stringToMD5(userTable.getPassword()));
        userTableService.save(userTable);

        return R.ok();
    }


    //传入excel文件，批量导入用户
    @ApiOperation("excel批量导入用户")
    @PostMapping("/excelCreate")
    public R excelCreate(@RequestParam("file") MultipartFile file) throws IOException, InvalidFormatException {
//        try {
//            TokenUtils.powerCheck(token, "导入用户");
//        } catch (TokenException tokenException) {
//            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
//        }

        userTableService.importExcel(file,userTableService);
        return R.ok();

//        if (multipartFile.isEmpty()) {
//            return R.error().setMessage("文件为空");
//        }
//        //文件上传前的名称
//        String fileName = multipartFile.getOriginalFilename();
//        File file = new File(fileName);
//        OutputStream out = null;
//        try {
//            //获取文件流，以文件流的方式输出到新文件
////    InputStream in = multipartFile.getInputStream();
//            out = new FileOutputStream(file);
//            byte[] ss = multipartFile.getBytes();
//            for (int i = 0; i < ss.length; i++) {
//                out.write(ss[i]);
//            }
//        } catch (IOException e) {
//            e.printStackTrace();
//        } finally {
//            if (out != null) {
//                try {
//                    out.close();
//                } catch (IOException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        if (!fileName.endsWith("xlsx") && !fileName.endsWith("xls")) {
//            File f = new File(file.toURI());
//            if (f.delete()) {
//                System.out.println("删除成功");
//            } else {
//                System.out.println("删除失败");
//            }
//            return R.error().setMessage("文件格式不正确，请传入xlsx或xls格式文件");
//        }
//
//        //使用服务层处理excel中的数据，实现导入
//        userTableService.ExcelImport(file);
//
//
//        // 操作完上的文件 需要删除在根目录下生成的文件
//        File f = new File(file.toURI());
//        if (f.delete()) {
//            System.out.println("删除成功");
//        } else {
//            System.out.println("删除失败");
//        }
//
//        return R.ok();
    }

    //下载模板excel
    @ApiOperation("下载excel模板")
    @PostMapping("/downloadExcel")
    public R downloadExcel(HttpServletResponse response, @RequestParam String token) throws IOException {
        try {
            TokenUtils.powerCheck(token, "下载模板");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
// 读到流中
        String path = "C:\\Users\\16270\\Desktop\\赛意练习\\模拟项目\\用户信息导入模板.xlsx";
        InputStream inputStream = new FileInputStream(path);// 文件的存放路径
        response.reset();
        response.setContentType("application/json;charset=utf-8");//application/octet-stream接受所有格式
        String filename = new File(path).getName();
        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
        ServletOutputStream outputStream = response.getOutputStream();
        byte[] b = new byte[1024];
        int len;
//从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
        while ((len = inputStream.read(b)) > 0) {
            outputStream.write(b, 0, len);
        }
        inputStream.close();

        return R.ok();
    }

    //批量导出用户
    @ApiOperation("excel批量导出用户")
    @PostMapping("/exportUsers")
        public R exportUsers(@RequestParam String[] userNames, @RequestParam String token, HttpServletResponse response) throws IOException {
        try {
            TokenUtils.powerCheck(token, "导出用户");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }

        //easyExcel
//        userTableService.exportExcel(response,userNames);




        //创建excel文件
        userTableService.exportUsers(userNames);
//
        String path = "C:\\Users\\16270\\Desktop\\赛意练习\\模拟项目\\导出用户信息表.xlsx";
//        // 读到流中
//        InputStream inputStream = new FileInputStream(path);// 文件的存放路径
//        response.reset();
//        response.setContentType("application/json;charset=utf-8");//application/octet-stream接受所有格式
//        String filename = new File(path).getName();
//        response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(filename, "UTF-8"));
//        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");
//        ServletOutputStream outputStream = response.getOutputStream();
//        byte[] b = new byte[1024];
//        int len;
////从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
//        while ((len = inputStream.read(b)) > 0) {
//            outputStream.write(b, 0, len);
//        }
//        inputStream.close();

        return R.ok().setMessage("导出到路径"+path);
    }

    //删除用户
    @ApiOperation("批量删除")
    @PostMapping("/deleteUser")
    public R deleteUser(@RequestParam String[] userNames, @RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "删除用户");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        if (userTableService.removeByIds(Arrays.asList(userNames))) {
            QueryWrapper<UserRole> queryWrapper = new QueryWrapper<>();
            queryWrapper.in("USER_NAME", userNames);
            userRoleService.remove(queryWrapper);
            return R.ok();
        }
        return R.error().setMessage("删除出现问题");
    }

    //修改用户
    @ApiOperation("修改用户")
    @PostMapping("/alterUser")
    public R alterUser(@RequestBody UserTable userTable, @RequestParam String token) {
        try {
            TokenUtils.powerCheck(token, "修改用户");
        } catch (TokenException tokenException) {
            return R.ok().setCode(tokenException.getCode()).setMessage(tokenException.getMessage());
        }
        if (userTableService.updateById(userTable)) {
            return R.ok();
        }
        return R.error().setMessage("修改出现问题");
    }
}
